package com.yami.shop.manager.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.yami.shop.bean.app.dto.ShopCartItemDto;
import com.yami.shop.bean.app.param.OrderItemParam;
import com.yami.shop.bean.enums.ProdType;
import com.yami.shop.bean.enums.ShopCityStatus;
import com.yami.shop.bean.enums.ShopStatus;
import com.yami.shop.bean.event.CheckAddrEvent;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.model.Sku;
import com.yami.shop.bean.vo.VirtualRemarkVO;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.Arith;
import com.yami.shop.common.util.Json;
import com.yami.shop.dao.BasketMapper;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.ShopDetailService;
import com.yami.shop.service.SkuService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

import static com.yami.shop.common.util.SpringContextUtils.applicationContext;

/**
 * 购物车适配器
 * @author FrozenWatermelon
 */
@Component
@AllArgsConstructor
public class ShopCartItemAdapter {

    private final BasketMapper basketMapper;

    private final SkuService skuService;

    private final ShopDetailService shopDetailService;

    private final ProductService productService;

    private final LangManager langManager;

    /**
     * 组装获取用户提交的购物车商品项
     * @param orderItem 提交订单时携带的商品信息
     * @param userId 当前用户的用户id
     * @return 所有的商品购物项
     */
    public List<ShopCartItemDto> getShopCartItemsByOrderItems(OrderItemParam orderItem, String userId, Long addrId) {
        // 当立即购买时，没有提交的订单是没有购物车信息的
        if (Objects.nonNull(orderItem)) {
            if (Objects.nonNull(orderItem.getComboId())) {
                return getComboShopCartItems(orderItem, userId, addrId);
            }
            return getShopCartItem(orderItem, null, userId, addrId);
        }

        List<ShopCartItemDto> dbShopCartItems = getShopCartItems(userId, addrId).stream().filter(ShopCartItemDto::getIsChecked).collect(Collectors.toList());

        if (CollUtil.isEmpty(dbShopCartItems)) {
            // 请选择您需要的商品加入购物车
            throw new YamiShopBindException("yami.selelct.items");
        }
        // 返回购物车选择的商品信息
        return dbShopCartItems;
    }

    /**
     * 根据用户ID获取购物车项内容列表
     * @param userId 用户ID
     * @return 购物车信息项列表
     */
    public List<ShopCartItemDto> getShopCartItems(String userId, Long addrId) {
        List<ShopCartItemDto> shopCartItemDtoList = basketMapper.getShopCartItems(userId);
        langManager.getShopCartItemDtoLang(shopCartItemDtoList);
        for (ShopCartItemDto shopCartItemDto : shopCartItemDtoList) {
            // 物流配送信息
            Product.DeliveryModeVO deliveryModeVO = Json.parseObject(shopCartItemDto.getDeliveryMode(), Product.DeliveryModeVO.class);
            shopCartItemDto.setDeliveryModeVO(deliveryModeVO);
            // 未开启同城配送
            if (!Objects.equals(ShopCityStatus.USABLE.value(), shopCartItemDto.getShopCityStatus())) {
                deliveryModeVO.setHasCityDelivery(false);
            }
            shopCartItemDto.setProductTotalAmount(Arith.mul(shopCartItemDto.getProdCount(), shopCartItemDto.getPrice()));
            shopCartItemDto.setActualTotal(shopCartItemDto.getProductTotalAmount());
            if (Objects.isNull(shopCartItemDto.getIsChecked())) {
                shopCartItemDto.setIsChecked(false);
            }
            if (StrUtil.isNotBlank(shopCartItemDto.getVirtualRemark())) {
                List<VirtualRemarkVO> virtualRemarkList = JSONUtil.parseArray(shopCartItemDto.getVirtualRemark()).toList(VirtualRemarkVO.class);
                virtualRemarkList.forEach(virtualRemark -> virtualRemark.setProdId(shopCartItemDto.getProdId()));
                shopCartItemDto.setVirtualRemarkList(virtualRemarkList);
            }
            if(Objects.equals(shopCartItemDto.getProdType(), ProdType.PROD_TYPE_ACTIVE.value()) || Objects.equals(shopCartItemDto.getMold(), 1) || Objects.equals(userId, null)){
                shopCartItemDto.setIsDelivery(true);
            }else {
                // 判断用户默认地址是否在配送区域内
                applicationContext.publishEvent(new CheckAddrEvent(addrId, userId, null, shopCartItemDto));
            }
        }
        return shopCartItemDtoList;
    }

    /**
     * 将参数转换成组装好的购物项
     * @param orderItem 购物车物品参数
     * @param activityPriceFee 活动价
     * @return 商品购物项
     */
    public List<ShopCartItemDto> getShopCartItem(OrderItemParam orderItem, Double activityPriceFee, String userId, Long addrId) {
        Sku sku = skuService.getSkuAndName(orderItem.getSkuId());
        if (Objects.isNull(sku)) {
            // 订单包含无法识别的商品
            throw new RuntimeException("yami.order.unrecognized.prod");
        }
        Product prod = productService.getProductAndLang(sku.getProdId());
        if (Objects.isNull(prod)) {
            // 订单包含无法识别的商品
            throw new RuntimeException("yami.order.unrecognized.prod");
        }
        if (orderItem.getProdCount() < 1) {
            // 下单商品数量不能小于1
            throw new RuntimeException("yami.order.prod.count.limit");
        }
        // 拿到购物车的所有item
        ShopCartItemDto shopCartItem = new ShopCartItemDto();
        shopCartItem.setBasketId(-1L);
        shopCartItem.setSkuId(sku.getSkuId());
        shopCartItem.setProdId(prod.getProdId());
        shopCartItem.setProdType(prod.getProdType());
        shopCartItem.setCategoryId(prod.getCategoryId());
        shopCartItem.setProdCount(orderItem.getProdCount());
        shopCartItem.setReceiverGroupId(orderItem.getReceiverGroupId());
        // 积分商品
        if (Objects.equals(prod.getProdType(), ProdType.PROD_TYPE_SCORE.value())) {
            shopCartItem.setScorePrice(sku.getSkuScore() * orderItem.getProdCount());
        }
        // 虚拟商品参数
        if (Objects.equals(prod.getMold(), 1)) {
            shopCartItem.setWriteOffNum(prod.getWriteOffNum());
            shopCartItem.setWriteOffMultipleCount(prod.getWriteOffMultipleCount());
            shopCartItem.setWriteOffStart(prod.getWriteOffStart());
            shopCartItem.setWriteOffEnd(prod.getWriteOffEnd());
            shopCartItem.setWriteOffTime(prod.getWriteOffTime());
            shopCartItem.setIsRefund(prod.getIsRefund());
            // 虚拟商品备注留言
            if (StrUtil.isNotBlank(prod.getVirtualRemark())) {
                List<VirtualRemarkVO> virtualRemarkList = JSONUtil.parseArray(prod.getVirtualRemark()).toList(VirtualRemarkVO.class);
                for (VirtualRemarkVO virtualRemarkVO : virtualRemarkList) {
                    if(virtualRemarkVO.getIsRequired() == null){
                        virtualRemarkVO.setIsRequired(false);
                    }
                    virtualRemarkVO.setProdId(shopCartItem.getProdId());
                }
                shopCartItem.setVirtualRemarkList(virtualRemarkList);
            }
        }
        shopCartItem.setMold(Objects.isNull(prod.getMold()) ? 0 : prod.getMold());
        shopCartItem.setSkuName(sku.getSkuName());
        shopCartItem.setProdName(prod.getProdName());
        shopCartItem.setCategoryId(prod.getCategoryId());
        shopCartItem.setPreSellTime(prod.getPreSellTime());
        shopCartItem.setPreSellStatus(prod.getPreSellStatus());
        shopCartItem.setPic(StrUtil.isBlank(sku.getPic()) ? prod.getPic() : sku.getPic());
        shopCartItem.setBasketDate(new Date());
        shopCartItem.setDistributionCardNo(orderItem.getDistributionCardNo());
        shopCartItem.setPrice(sku.getPrice());
        shopCartItem.setProductTotalAmount(Arith.mul(sku.getPrice(), orderItem.getProdCount()));
        // 初始化商品实际金额
        shopCartItem.setActualTotal(shopCartItem.getProductTotalAmount());
        shopCartItem.setShareReduce(0.0);
        // 如果有活动价并且活动价大于0则使用活动价格
        if (activityPriceFee != null && activityPriceFee > 0.0) {
            // 商品实际金额，优惠金额放入店铺金额
            shopCartItem.setPrice(activityPriceFee);
            // 商品实际金额 = 商品总金额 - 分摊的优惠金额 - 分摊的积分抵现金额
            shopCartItem.setActualTotal(Arith.mul(shopCartItem.getProdCount(), activityPriceFee));
            double shareReduce = Math.max(Arith.sub(shopCartItem.getProductTotalAmount(), shopCartItem.getActualTotal()), 0.0);
            shopCartItem.setShareReduce(shareReduce);
            // 如果活动价大于商品价格，则设置下原价
            shopCartItem.setProductTotalAmount(Arith.mul(shopCartItem.getPrice(), orderItem.getProdCount()));
        }
        // 物流配送信息
        shopCartItem.setDeliveryMode(prod.getDeliveryMode());
        shopCartItem.setDeliveryTemplateId(prod.getDeliveryTemplateId());
        shopCartItem.setDeliveryAmount(prod.getDeliveryAmount());
        Product.DeliveryModeVO deliveryModeVO = Json.parseObject(shopCartItem.getDeliveryMode(), Product.DeliveryModeVO.class);
        shopCartItem.setDeliveryModeVO(deliveryModeVO);
        if (prod.getShopId() == 0) {
            shopCartItem.setShopId(Constant.PLATFORM_SHOP_ID);
            shopCartItem.setShopName(Constant.PLATFORM_SHOP_NAME);
        } else {
            ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(prod.getShopId());
            if (!Objects.equals(shopDetail.getShopStatus(), ShopStatus.OPEN.value())) {
                // 店铺不处于营业状态
                throw new YamiShopBindException("yami.store.shop.state.check");
            }
            shopCartItem.setShopId(shopDetail.getShopId());
            shopCartItem.setShopName(shopDetail.getShopName());
        }
        shopCartItem.setVolume(sku.getVolume());
        shopCartItem.setWeight(sku.getWeight());
        if(Objects.equals(shopCartItem.getProdType(), ProdType.PROD_TYPE_ACTIVE.value()) || Objects.equals(shopCartItem.getMold(), 1) || Objects.equals(userId, null)){
            shopCartItem.setIsDelivery(true);
        }else {
            // 判断用户默认地址是否在配送区域内
            applicationContext.publishEvent(new CheckAddrEvent(addrId, userId, null, shopCartItem));
        }
        //return Collections.singletonList(shopCartItem);
        List<ShopCartItemDto> shopCartItems = new ArrayList<>();
        shopCartItems.add(shopCartItem);
        return shopCartItems;
    }

    private List<ShopCartItemDto> getComboShopCartItems(OrderItemParam orderItem, String userId, Long addrId) {
        List<ShopCartItemDto> shopCartItems = new ArrayList<>();
        ShopCartItemDto mainShopCartItem = getShopCartItem(orderItem, null, userId, addrId).get(0);
        if (orderItem.getProdCount() < 1) {
            orderItem.setProdCount(1);
        }
        mainShopCartItem.setIsMainProd(1);
        shopCartItems.add(mainShopCartItem);
        if (CollUtil.isNotEmpty(orderItem.getMatchingSkuIds())) {
            for (Long skuId : orderItem.getMatchingSkuIds()) {
                OrderItemParam matchingOrderItem = new OrderItemParam();
                matchingOrderItem.setSkuId(skuId);
                matchingOrderItem.setComboId(orderItem.getComboId());
                matchingOrderItem.setProdCount(orderItem.getProdCount());
                ShopCartItemDto matchingShopCartItem = getShopCartItem(matchingOrderItem, null, userId, addrId).get(0);
                matchingShopCartItem.setIsMainProd(0);
                shopCartItems.add(matchingShopCartItem);
            }
        }
        for (ShopCartItemDto shopCartItem : shopCartItems) {
            shopCartItem.setComboId(orderItem.getComboId());
            shopCartItem.setComboCount(orderItem.getProdCount());
            shopCartItem.setProdCount(0);
        }
        return shopCartItems;
    }
}
